const express = require('express'),
    router = express.Router(),
    tableModel = require('../models/tableModel')

router.get('/queryTable', (req, res) => {
    let { page, limit } = req.query;
    page = Number(page);
    limit = Number(limit);
    queryTable(page, limit).then(result => {
        res.send({ sumPages: result.sumPages, list: result.list });
    });
});

/**
 * 
 * @param {第一页} page 
 * @param {每页多少条} limit 
 */
function queryTable(page = 1, limit = 10) {
    return new Promise((resolve, reject) => {

        let sumPages = 0;
        tableModel.countDocuments().then(count => {
            sumPages = Math.ceil(count / limit);
            page = Math.min(page, sumPages);
            page = Math.max(page, 1);

            let skip = (page - 1) * limit;

            tableModel.find().limit(limit).skip(skip).then(res => {
                resolve({
                    sumPages,
                    list: res
                });
            });
        });

    });
}



// for (let i = 0; i < 100; i++) {
//     let table = new tableModel({
//         id: i,
//         text: `${i}号种子选手`
//     });
//     table.save();
// }

// tableModel.find().limit(2).then(res => {
//     console.log(res);
// });


module.exports = router;